namespace RBAC.Read.Api.Application.Handler.BomHandler
{
    using MediatR;
    using Microsoft.Extensions.Logging;
    using RBAC.Domain.BomManage;
    using RBAC.ErrorCode;
    using RBAC.Interstructrue.Base;
    using RBAC.Read.Api.Application.Command.BomCommand;
    using RBAC.Read.Api.Application.Dto.Bom;

    /// <summary>
    /// 按Id获取BOM详情 处理器
    /// </summary>
    public class GetBomDetailByIdHandler : IRequestHandler<GetBomDetailByIdCommand, APIResult<BomDetailDto>>
    {
        private readonly IBaseRepository<Bom> repository;
        private readonly IBaseRepository<Product> productRepository;
        private readonly ILogger<GetBomDetailByIdHandler> logger;

        public GetBomDetailByIdHandler(IBaseRepository<Bom> repository, IBaseRepository<Product> productRepository, ILogger<GetBomDetailByIdHandler> logger)
        {
            this.repository = repository;
            this.productRepository = productRepository;
            this.logger = logger;
        }

        public Task<APIResult<BomDetailDto>> Handle(GetBomDetailByIdCommand request, CancellationToken cancellationToken)
        {
            var result = new APIResult<BomDetailDto>();
            try
            {
                cancellationToken.ThrowIfCancellationRequested();

                if (request.Id <= 0)
                {
                    result.Code = APIEnums.Fail;
                    result.Msg = "参数无效：Id 必须大于 0";
                    result.Data = default!;
                    return Task.FromResult(result);
                }

                var model = repository.GetFirstOrDefault("Id = @Id AND IsDeleted = 0", new { request.Id });
                if (model == null)
                {
                    result.Code = APIEnums.Fail;
                    result.Msg = "未找到对应的BOM";
                    result.Data = default!;
                }
                else
                {
                    // 查询产品信息
                    string? productCode = null;
                    string? productName = model.ProductName; // 兼容历史字段
                    if (model.ProductId > 0)
                    {
                        var product = productRepository.GetFirstOrDefault("Id = @Id AND IsDeleted = 0", new { Id = model.ProductId });
                        if (product != null)
                        {
                            productCode = product.Code;
                            productName = product.Name;
                        }
                    }

                    var dto = new BomDetailDto
                    {
                        Id = model.Id,
                        Code = model.Code,
                        Name = model.Name,
                        ProductId = model.ProductId,
                        ProductCode = productCode,
                        ProductName = productName,
                        Version = model.Version,
                        Unit = model.Unit,
                        Status = model.Status,
                        RevisionNotes = model.RevisionNotes,
                        CreateUser = model.CreateUser,
                        CreateTime = model.CreateTime,
                    };

                    result.Code = APIEnums.Success;
                    result.Msg = "获取BOM详情成功";
                    result.Data = dto;
                }
            }
            catch (OperationCanceledException)
            {
                logger.LogWarning("获取BOM详情被取消");
                result.Code = APIEnums.Error;
                result.Msg = "请求已取消";
                result.Data = default!;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "获取BOM详情失败: {Message}", ex.Message);
                result.Code = APIEnums.Error;
                result.Msg = "获取BOM详情失败";
                result.Data = default!;
            }

            return Task.FromResult(result);
        }
    }
}
